package com.moment.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.jws.WebParam;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;



import com.moment.model.GlobalClass;
import com.moment.util.Converter;
import com.moment.webservice.Services;
import com.moment.webservice.ServicesProxy;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class RegistrationController
 */
@WebServlet("/RegistrationController")
public class RegistrationController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RegistrationController() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doCall(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doCall(request, response);
	}

	/*
	 * public static String fileToBase64() {
	 * 
	 * 
	 * 
	 * // For Convert Drawable to Bitmap photo =
	 * ((BitmapDrawable)d).getBitmap(); ByteArrayOutputStream bao = new
	 * ByteArrayOutputStream(); photo.compress(Bitmap.CompressFormat.JPEG, 90,
	 * bao); byte [] ba = bao.toByteArray(); imagecode=Base64.encodeBytes(ba);
	 * return imagecode; }
	 */
	protected void doCall(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String callto = request.getParameter("callto");

		System.out.println("callto --" + callto);
		if (callto == null) {
			HttpSession session = request.getSession();
			String mob = (String) session.getAttribute("mob");
			String name = (String) session.getAttribute("name");
			String email = (String) session.getAttribute("email");
			Map<String, String> map = new HashMap<String, String>();
			map.put("method", "3");
			map.put("mnum", mob);
			map.put("username", name);
			map.put("email", email);

			try {
				List<FileItem> items = new ServletFileUpload(
						new DiskFileItemFactory()).parseRequest(request);

				for (FileItem item : items) {
					if (item.isFormField()) {
						// Process regular form field (input
						// type="text|radio|checkbox|etc", select, etc).
						String fieldname = item.getFieldName();
						String fieldvalue = item.getString();
						System.out.println(fieldname + ":" + fieldvalue);
						if (fieldname.equals("lat")) {
							map.put(fieldname, fieldvalue);
						} else if (fieldname.equals("longi")) {
							map.put(fieldname, fieldvalue);

						} else if (fieldname.equals("password")) {
							map.put(fieldname,
									GlobalClass.encryptpass(fieldvalue));

						} else if (fieldname.equals("q1")) {
							map.put("ques1", fieldvalue);

						} else if (fieldname.equals("q2")) {
							map.put("ques2", fieldvalue);

						} else if (fieldname.equals("q3")) {
							map.put("ques3", fieldvalue);

						} else if (fieldname.equals("a1")) {
							map.put("ans1", fieldvalue);
						} else if (fieldname.equals("a2")) {
							map.put("ans2", fieldvalue);
						} else if (fieldname.equals("a3")) {
							map.put("ans3", fieldvalue);
						} else if (fieldname.equals("type")) {
							map.put(fieldname, fieldvalue);
						}
					} else {
						System.out.println("item .getCotenttype:"
								+ item.getContentType());
						String[] typeOfImage=item.getContentType().split("/");
						if(typeOfImage[1].equalsIgnoreCase("jpeg")||typeOfImage[1].equalsIgnoreCase("png")||typeOfImage[1].equalsIgnoreCase("jpg")){
						String base64String = Base64.encode(item.get());
						System.out.println("Base 64 string of Img:"
								+ base64String);
						map.put("img", base64String);
						}else{
							session.setAttribute("error", "Img Wrong !!!!");
							response.sendRedirect("jsp/registration.jsp");
						}
					
					}

				}
				System.out.println("Key : Value");
				for (Map.Entry<String, String> entry : map.entrySet()) {
					System.out.println(entry.getKey() + ":" + entry.getValue());
				}
				String json = new Converter().mapToJson(map);
				System.out.println("json String :" + json);
				Services serviceproxy = new ServicesProxy();
				String output = serviceproxy.service(json);
				System.out.println("data from webservices" + output);

				if (output.equalsIgnoreCase("Success")) {
					session.invalidate();
					response.sendRedirect("jsp/index.jsp");

				} else {

					session.setAttribute("error", "SomeThing Wrong !!!!");
					response.sendRedirect("jsp/registration.jsp");

				}

			} catch (FileUploadException e) {
				throw new ServletException("Cannot parse multipart request.", e);
			}

		} else if (callto.equalsIgnoreCase("getotp")) {
			String mob = request.getParameter("mnum");
			String name = request.getParameter("name");
			String email = request.getParameter("email");
			HttpSession session = request.getSession();
			// --New CODE-------------
			Map<String, String> map = new HashMap<String, String>();
			map.put("method", "1");
			map.put("mnum", mob);
			map.put("email", email);
			String json = new Converter().mapToJson(map);
			System.out.println("json String :" + json);
			Services serviceproxy = new ServicesProxy();
			String output = serviceproxy.service(json);
			// ---------------------------

			/*
			 * WebsProxy proxy = new WebsProxy(); String h =
			 * proxy.mobileVerification(mob, email);
			 */
			System.out.println("output:=" + output);
			if (output.equals("Success")) {
				session.setAttribute("mob", mob);
				session.setAttribute("name", name);
				session.setAttribute("email", email);
				response.sendRedirect("jsp/otpverify.jsp");

			} else {

				session.setAttribute("error", "Fail");
				response.sendRedirect("jsp/register.jsp");

			}

		} else if (callto.equalsIgnoreCase("checkotp")) {
			System.out.println();
			HttpSession session = request.getSession();
			String otp = request.getParameter("otp");
			String mob = (String) request.getSession().getAttribute("mob");
			// --New CODE-------------
			Map<String, String> map = new HashMap<String, String>();
			map.put("method", "2");
			map.put("otp", otp);
			map.put("mnum", mob);
			String json = new Converter().mapToJson(map);
			System.out.println("json String :" + json);
			Services serviceproxy = new ServicesProxy();
			String output = serviceproxy.service(json);
			// ---------------------------

			/*
			 * WebsProxy proxy = new WebsProxy(); String output =
			 * proxy.checkingOTP(mob, otp);
			 */
			System.out.println("output from webservice:" + output + " " + mob);
			if (output.equalsIgnoreCase("Success")) {
				System.out.println();
				response.sendRedirect("jsp/registration.jsp");

			} else {

				session.setAttribute("error", "OTP FAIL");
				response.sendRedirect("jsp/otpverify.jsp");

			}

		} else {// callto=submit form
			// register

		}

	}
}
